package com.gjt.serverSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.Channels;
import java.nio.channels.CompletionHandler;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 异步通道： 读写异步通道会立即返回，甚至在io 之前返回。 连接和 接收 方法也会异步/
 */
public class AsynchronousChannel {

    public static void main(String[] args) {
        SocketAddress address = new InetSocketAddress(args[0], 80);
        try {
            AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
            Future<Void> connect = client.connect(address);

            ByteBuffer buffer = ByteBuffer.allocate(100);

            // 等待连接完成
            connect.get();

            //  从链接中读取数据
            Future<Integer> read = client.read(buffer);
            // 做其他工作


            // 等待读取完成
             read.get();

             // 翻转缓冲区并排空
            buffer.flip();
            WritableByteChannel out = Channels.newChannel(System.out);
            out.write(buffer);




            // 读取缓冲区时

            CompletionHandler<Integer, ByteBuffer> lineHandler = new LineHandler();
            // 传入一个缓冲区，附件，CompletionHandler   把缓冲区本身作为 附件本身
            client.read(buffer, buffer, lineHandler);
        } catch (ExecutionException | InterruptedException | IOException e) {
            throw new RuntimeException(e);
        }
    }

}
